﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Gizmox.WebGUI.Forms;
using TVC.Modules.CustomControl;
using TVC.Layout;
using System.Data;


namespace TVC.Modules
{
    public class ModuleParent : Gizmox.WebGUI.Forms.UserControl
    {
        protected System.Globalization.CultureInfo mobjCustomCulture;
        protected System.Globalization.CultureInfo mobjSavedCulture = null;
        protected ErrorProvider errProvider = new ErrorProvider();
        protected ErrorProvider warnProvider = new ErrorProvider();
        protected DataGridView _dgvList = null;
        protected TreeView _tvList = null;
        protected GridFilter _dgvFilter = null;
        protected TabControl _tabControl = null;

        public bool Cancel;
        public string _processStatus;
        public string _strType;
        public string _strTableName;
        public string sErr = "";

        protected GridLayout _layout = null;

        protected enum ErrorStatus
        {
            ERROR,
            WARNING,
            SUCCESS
        }
        
        /// <summary>
        /// Add New record  if not having data in Form
        ///                 else Confirm Copy record
        /// </summary>
        /// <param name="keyControl">Primary Key Control</param>
        public virtual void AddNew(Control keyControl)
        {
            if (keyControl.Text != "")
            {
                //MessageBox.Show("Do you want to copy from the " + keyControl.Text + " record?", "Copy", MessageBoxButtons.YesNo, MessageBoxIcon.Question, delegate(object newSender, EventArgs newArgs)
                //{
                //    if (((MessageBoxWindow)newSender).DialogResult != DialogResult.Yes)
                //    {

                _processStatus = "C";
                refreshForm("");
                SetupToolBar(_processStatus);
                //}
                //else
                //{
                //    _processStatus = "O";
                //    SetupToolBar(_processStatus);
                //}
                if (_tabControl != null) _tabControl.SelectedIndex = 1;
                enableForm(true);
                keyControl.Focus();

                //});
            }
            else
            {
                if (_tabControl != null) _tabControl.SelectedIndex = 1;
                enableForm(true);
                refreshForm("");
                keyControl.Focus();
                _processStatus = "C";
                SetupToolBar(_processStatus);
            }
        }
        /// <summary>
        /// Edit record of Form
        /// </summary>
        /// <param name="keyControls">Primary Key Control</param>        
        public virtual void editRecord(params Control[] keyControls)
        {
            foreach (Control x in keyControls)
            {
                if (x.Text == "")
                {
                    MessageBox.Show("DO NOT edit blank " + this.Text, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning, false);
                    return;
                }

            }
            if (_tabControl != null) _tabControl.SelectedIndex = 1;
            SetupToolBar("A");
            enableForm(true);
            foreach (Control x in keyControls)
            {
                x.Enabled = false;

            }
            keyControls[0].Parent.Focus();

            _processStatus = "A";
        }
        /// <summary>
        /// Copy record of Form
        /// </summary>
        /// <param name="keyControl">Primary Key Control</param>      
        protected virtual void copy(Control keyControl)
        {
            if (keyControl.Text == "")
            {
                MessageBox.Show("DO NOT copy blank " + this.Text, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning, false);
                return;
            }

            if (_tabControl != null) _tabControl.SelectedIndex = 1;
            _processStatus = "O";

            SetupToolBar(_processStatus);
            enableForm(true);
            keyControl.Focus();


        }

        /// <summary>
        /// Show List data
        /// </summary>
        protected virtual void list()
        {
            if (_tabControl != null) _tabControl.SelectedIndex = 0;
        }

        /// <summary>
        /// Delete data
        /// </summary>
        /// <param name="keyControl">Primary Key Control</param>
        /// <param name="isDraft">true if not validate</param>
        public virtual void saveRecord(Control keyControl, bool isDraft = false)
        {
            sErr = "";
            string saveProcess = _processStatus;
            ErrorStatus s = ErrorStatus.SUCCESS;
            if (!isDraft) s = validateForm(ref sErr);

            string confirmMsg = "";

            if (s == ErrorStatus.ERROR)
            {
                MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                _processStatus = saveProcess;
                //SetupToolBar(_processStatus);
                return;
            }
            else if (s == ErrorStatus.WARNING)
            {
                confirmMsg = sErr;
                //MessageBox.Show(sErr, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, false);
            }



            if (_processStatus == "C" || _processStatus == "O")
            {
                if (checkExists())
                {
                    if (keyControl != null) keyControl.Focus();
                    if (_strsErrcheckExists != "")
                    {
                        MessageBox.Show(_strsErrcheckExists, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                    }
                    else
                        MessageBox.Show("Your " + keyControl.Text + " record has already existed!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);

                    _processStatus = saveProcess;
                    return;
                }

                if (!isDraft)
                {
                    string sErr1 = "";
                    ErrorStatus sAdd = beforeAdd(ref sErr1);
                    if (sAdd == ErrorStatus.ERROR)
                    {
                        MessageBox.Show(sErr1, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                        _processStatus = saveProcess;
                        return;
                    }
                    else if (sAdd == ErrorStatus.WARNING)
                    {
                        confirmMsg += sErr1 + "\n";
                    }
                }

                if (confirmMsg != "")
                {
                    confirmMsg += "Would you like to add this Record?";
                    if (keyControl.Name == "MovementType")//|| keyControl.Name == "txtItemCode")
                    {
                        AddNewStep2(keyControl, isDraft);
                    }
                    else
                    {
                        MessageBox.Show(confirmMsg, "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, delegate(object newSender, EventArgs newArgs)
                        {
                            if (((MessageBoxWindow)newSender).DialogResult == DialogResult.OK) AddNewStep2(keyControl, isDraft);
                            else _processStatus = saveProcess;
                        }, false);
                    }

                }
                else
                {
                    AddNewStep2(keyControl, isDraft);
                }
            }
            else
            {
                if (!isDraft)
                {
                    string sErr1 = "";
                    ErrorStatus sUpdate = beforeUpdate(ref sErr1);
                    if (sUpdate == ErrorStatus.ERROR)
                    {
                        MessageBox.Show(sErr1, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                        _processStatus = saveProcess;
                        return;
                    }
                    else if (sUpdate == ErrorStatus.WARNING)
                    {
                        confirmMsg += sErr1 + "\n";
                    }
                }


                if (confirmMsg != "")
                {
                    //confirmMsg += "Would you like to add this Record?";
                    MessageBox.Show(confirmMsg, "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, delegate(object newSender, EventArgs newArgs)
                    {
                        if (((MessageBoxWindow)newSender).DialogResult == DialogResult.OK)
                        {
                            sErr = updateRecord(isDraft);

                            if (sErr == "")
                            {
                                enableForm(false);
                                reloadList();
                                afterUpdate();
                                if (keyControl.Name == "MovementType" || keyControl.Name == "txtItemCode")
                                { }
                                else
                                    MessageBox.Show("Your record is updated successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information, false);
                                _processStatus = "S";
                                SetupToolBar(_processStatus);
                            }
                            else
                            {
                                MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                                _processStatus = "A";
                            }
                        }
                        else _processStatus = saveProcess;
                    }, false);
                }
                else
                {
                    sErr = updateRecord(isDraft);

                    if (sErr == "")
                    {
                        enableForm(false);
                        reloadList();
                        afterUpdate();
                        if (keyControl.Name == "MovementType" || keyControl.Name == "txtItemCode")
                        { }
                        else
                            MessageBox.Show("Your record is updated successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information, false);
                        _processStatus = "S";
                        SetupToolBar(_processStatus);
                    }
                    else
                    {
                        MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                        _processStatus = "A";
                    }
                }
                //confirmMsg += " Would you like to update this Record?";
                //MessageBox.Show(confirmMsg, "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, delegate(object newSender, EventArgs newArgs)
                //{
                //    if (((MessageBoxWindow)newSender).DialogResult == DialogResult.OK)
                //    {

                //}
                //else { _processStatus = "A"; }
                //});
            }

        }
        /// <summary>
        /// Delete data
        /// </summary>
        /// <param name="keyControl">Primary Key Control</param>
        public virtual void delete(Control keyControl)
        {
            string confirmMsg = "";
            if (keyControl.Text == "")
            {
                MessageBox.Show("DO NOT delete blank " + this.Text + "!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, false);
                return;
            }

            if (checkExists())
            {
                ErrorStatus sDel = beforeDelete(ref sErr);
                if (sDel == ErrorStatus.ERROR)
                {
                    MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                    return;
                }
                else if (sDel == ErrorStatus.WARNING)
                {
                    confirmMsg += sErr + "\n";
                }
                if (keyControl.Name == "MovementType")
                {
                    confirmMsg += " Would you like to delete this record? ";
                }
                else
                {
                    confirmMsg += " Would you like to delete " + keyControl.Text + " record?";
                }
                MessageBox.Show(confirmMsg, "Delete", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, delegate(object newSender, EventArgs newArgs)
                {
                    if (((MessageBoxWindow)newSender).DialogResult == DialogResult.OK)
                    {
                        sErr = delRecord();
                        if (sErr == "")
                        {
                            reloadList();
                            afterDelete();
                            refreshForm("");
                            enableForm(false);
                            MessageBox.Show(" Successfully deleted !", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information, false);
                        }
                        else
                        {
                            MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);

                        }
                        _processStatus = "V";
                    }
                    else
                    {
                        _processStatus = "V";
                    }
                }, false);
            }
            else
            {
                MessageBox.Show("Your record DON'T exists!", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning, false);
            }
        }
        /// <summary>
        /// Skip your process
        /// </summary>
        protected virtual void skip()
        {
            if (_processStatus != "C")
            {
                selectRecord();
                enableForm(false);
            }
            else
            {
                refreshForm("");

                enableForm(false);
                _processStatus = "V";
                SetupToolBar("V");
            }

        }
        /// <summary>
        /// Load current record to form
        /// </summary>
        protected virtual void selectRecord()
        {
            if (_dgvList != null)
            {

                if (_dgvList.DataSource is BindingSource)
                {
                    if (((BindingSource)_dgvList.DataSource).DataSource == null) return;
                }
                object info = null;
                if (_dgvList.CurrentRow != null && _dgvList.CurrentRow.DataBoundItem != null) info = _dgvList.CurrentRow.DataBoundItem;

                cancel(info);
            }
            else if (_tvList != null)
            {
                object info = _tvList.SelectedNode.Tag;
                cancel(info);
            }

        }

        private void cancel(object info)
        {
            //if (_processStatus == "C" || _processStatus == "A" || _processStatus == "O")
            //{
            //    MessageBox.Show("Do you want to skip your process?", "Copy", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, delegate(object newSender, EventArgs newArgs)
            //    {
            //        if (((MessageBoxWindow)newSender).DialogResult == DialogResult.OK)
            //        {
            //            loadRecord(info);
            //            enableForm(false);

            //            _processStatus = "V";
            //            SetupToolBar(_processStatus);
            //        }


            //    });

            //}
            //else
            //{
            loadRecord(info);
            enableForm(false);

            _processStatus = "V";
            SetupToolBar(_processStatus);
            //}
        }
        /// <summary>
        /// Subfunction for Add New function
        /// </summary>
        /// <param name="isDraft">true if not validate</param>
        private void AddNewStep2(Control keyControl, bool isDraft = false)
        {
            sErr = addRecord(isDraft);

            if (sErr == "")
            {
                enableForm(false);
                reloadList();
                afterAddNew();
                if (keyControl.Name == "MovementType" || keyControl.Name == "txtItemCode")
                { }
                else
                    MessageBox.Show("Your record is added successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information, false);
                _processStatus = "S";
                SetupToolBar(_processStatus);
            }
            else
            {
                MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                _processStatus = "C";
            }
        }
        /// <summary>
        /// Reload data for List
        /// </summary>
        protected virtual void reloadList()
        {
            if (_dgvFilter != null) _dgvFilter.btnOK_Click(null, null);

            if (_dgvList != null && _dgvList.ShowFilterRow == true && _dgvList.ContextMenu != null)
            {
                if (_dgvList.ContextMenu.MenuItems.Count >= 2) _dgvList.ContextMenu.MenuItems[1].Checked = true;
            }
        }

        /// <summary>
        /// You need override this function to add record
        /// Using transaction in function
        /// </summary>
        /// <param name="isDraft">true if not validate</param>
        /// <returns>String.Empty if not having Error</returns>
        protected virtual string addRecord(bool isDraft = false) { return ""; }
        /// <summary>
        /// You need override this function to delete record
        /// Using transaction in function
        /// </summary>        
        /// <returns>String.Empty if not having Error</returns>
        protected virtual string delRecord() { return ""; }
        /// <summary>
        /// You need override this function to udpate record
        /// Using transaction in function
        /// </summary>
        /// <param name="isDraft">true if not validate</param>
        /// <returns>String.Empty if not having Error</returns>
        protected virtual string updateRecord(bool isDraft = false) { return ""; }

        /// <summary>
        /// Validate data before Addnew
        /// </summary>
        /// <param name="sErr">Error Message if Having Error</param>
        /// <returns>true if is valide</returns>
        protected virtual ErrorStatus beforeAdd(ref string sErr) { return ErrorStatus.SUCCESS; }
        /// <summary>
        /// Validate data before Update
        /// </summary>
        /// <param name="sErr">Error Message if Having Error</param>
        /// <returns>true if is valide</returns>
        protected virtual ErrorStatus beforeUpdate(ref string sErr) { return ErrorStatus.SUCCESS; }
        /// <summary>
        /// Validate data before Delete
        /// </summary>
        /// <param name="sErr">Error Message if Having Error</param>
        /// <returns>true if is valide</returns>
        protected virtual ErrorStatus beforeDelete(ref string sErr) { return ErrorStatus.SUCCESS; }

        protected virtual ErrorStatus validateForm(ref string sErr) { return ErrorStatus.SUCCESS; }

        /// <summary>
        /// Raise when Update successful
        /// </summary>
        protected virtual void afterUpdate() { }
        /// <summary>
        /// Raise when Add new successful
        /// </summary>
        protected virtual void afterAddNew() { }
        /// <summary>
        /// Raise when Delete successful
        /// </summary>
        protected virtual void afterDelete() { }

        /// <summary>
        /// Check data exists in database
        /// </summary>
        /// <returns>true if exists</returns>
        protected virtual bool checkExists() { return true; }

        /// <summary>
        /// Load data to form
        /// </summary>
        /// <param name="o">Current datarowview</param>
        protected virtual void loadRecord(object o) { }
        /// <summary>
        /// get data object from form
        /// </summary>
        /// <returns>record</returns>
        protected virtual object getRecord() { return null; }
        /// <summary>
        /// refresh data of form
        /// </summary>
        /// <param name="val">default: string.Empty</param>
        protected virtual void refreshForm(string val) { }
        /// <summary>
        /// Enable of disable form
        /// </summary>
        /// <param name="val">Enable form when val is true</param>
        protected virtual void enableForm(bool val) { }

        public virtual void refresh() { }

        public virtual void reloadReference() { }

        /// <summary>
        /// Reset Grid Layout
        /// </summary>
        protected virtual void resetLayout()
        {
            if (_dgvList == null) return;

            if (_layout == null) _layout = new GridLayout(MainForm.ServerPath + "Resources\\Layout\\", String.Format("{0}Documents\\Layout\\{1}\\", MainForm.ServerPath, GetMainForm().PODInfo.USER_ID), _strType);

            _layout.ResetLayout();
            _layout.SetUpDGV(_dgvList);
        }
        /// <summary>
        /// Change Filter Type
        /// </summary>
        /// <param name="objArgs"></param>
        protected virtual void changeFilter(MenuItemEventArgs objArgs)
        {
            if (objArgs.MenuItem.Checked == false)
            {
                objArgs.MenuItem.Checked = true;
                _dgvList.ShowFilterRow = true;
            }
            else
            {
                objArgs.MenuItem.Checked = false;
                _dgvList.ShowFilterRow = false;
            }
        }
        /// <summary>
        /// Save Grid Layout
        /// </summary>
        protected virtual void saveLayout()
        {
            if (_dgvList == null) return;

            if (_layout == null) _layout = new GridLayout(MainForm.ServerPath + "Resources\\Layout\\", MainForm.ServerPath + "Documents\\Layout\\" + GetMainForm().PODInfo.USER_ID + "\\", _strType);
            _layout.GetUpDGV(_dgvList);
            _layout.SaveLayout();
        }

        /// <summary>
        /// Export current data to Excel
        /// </summary>
        protected virtual void export2Excel()
        {
            if (_dgvList == null) return;

            DataTable dtbBG = new DataTable(_strType);
            dtbBG.TableName = (GetMainForm().PODInfo.Business_ID == "HL" ? _strType : "Budget1");

            if (_dgvList.DataSource is DataTable) dtbBG = _dgvList.DataSource as DataTable;
            else if (_dgvList.DataSource is BindingSource)
            {
                if (((BindingSource)_dgvList.DataSource).DataSource is DataTable) dtbBG = ((BindingSource)_dgvList.DataSource).DataSource as DataTable;

            }

            Forms.frmTransferOut frmTO = new Forms.frmTransferOut(_strType, dtbBG.DefaultView.ToTable(), GetMainForm());
            frmTO.ExportToExcel();
        }
        /// <summary>
        /// Export current data to Excel
        /// </summary>
        protected virtual void export2Xml()
        {
            if (_dgvList == null) return;

            DataTable dtbBG = new DataTable(_strType);
            dtbBG.TableName = (GetMainForm().PODInfo.Business_ID == "HL" ? _strType : "Budget1");

            if (_dgvList.DataSource is DataTable) dtbBG = _dgvList.DataSource as DataTable;
            else if (_dgvList.DataSource is BindingSource)
            {
                if (((BindingSource)_dgvList.DataSource).DataSource is DataTable) dtbBG = ((BindingSource)_dgvList.DataSource).DataSource as DataTable;

            }

            Forms.frmTransferOut frmTO = new Forms.frmTransferOut(_strType, dtbBG.DefaultView.ToTable(), GetMainForm());
            frmTO.ExportToXml();
        }

        protected virtual void importData()
        {
            Forms.frmTransferIn frmTI = new Forms.frmTransferIn(_strType, GetMainForm());
            frmTI.FormClosed += delegate(object form, FormClosedEventArgs args)
            {
                if (((Gizmox.WebGUI.Forms.Form)form).DialogResult == DialogResult.OK)
                {
                    reloadList();
                    refreshForm("");
                    enableForm(false);
                }

            };
            frmTI.ShowDialog();
        }

        private void _dgvList_MenuClick(object objSource, MenuItemEventArgs objArgs)
        {
            if (objArgs.MenuItem.Tag != null)
            {
                if (objArgs.MenuItem.Tag.ToString().ToUpper() == "SAVE")
                {
                    saveLayout();
                }
                else if (objArgs.MenuItem.Tag.ToString().ToUpper() == "FILTER")
                {
                    changeFilter(objArgs);
                }
                else if (objArgs.MenuItem.Tag.ToString().ToUpper() == "RESET")
                {
                    resetLayout();
                }
            }
        }
        private void _dgvList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (_processStatus == "C" || _processStatus == "A" || _processStatus == "O")
            {
                MessageBox.Show("Do you want to skip your process?", "Copy", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, delegate(object newSender, EventArgs newArgs)
                {
                    if (((MessageBoxWindow)newSender).DialogResult == DialogResult.OK)
                    {
                        selectRecord();
                    }
                }, false);

            }
            else
            {
                selectRecord();
            }


        }



        public MainForm MainForm { get; set; }
        public string _title;
        protected List<MyPermisControl> _permisControl = new List<MyPermisControl>();
        public string language { get { return MainForm.Language; } }
        protected virtual void InitPermisControl() { }

        protected void FormatDate()
        {
            if (mobjCustomCulture == null)
            {
                mobjCustomCulture = System.Globalization.CultureInfo.CreateSpecificCulture(System.Threading.Thread.CurrentThread.CurrentCulture.Name);
                string[] myDateTimePatterns = new string[] { "dd/MM/yyyy", "dd/MM/yyyy", "dd/MM/yyyy" }; //{ "ddd dd/MM/yy", "ddd dd/MM/yyyy", "dd/MM/yyyy" };
                mobjCustomCulture.DateTimeFormat.SetAllDateTimePatterns(myDateTimePatterns, 'd');
                
            }
            //if (mobjSavedCulture == null)
            //    mobjSavedCulture = System.Threading.Thread.CurrentThread.CurrentCulture;

            System.Threading.Thread.CurrentThread.CurrentCulture = mobjCustomCulture;
            VWGContext.Current.CurrentUICulture = mobjCustomCulture;
        }
        public ToolBar TbarLocal { get; set; }
        protected ToolBar GetTbarLocal()
        {
            if (TbarLocal != null) return TbarLocal;
            if (this.Parent.Controls["mobjToolBarMain"] is ToolBar) return TbarLocal = this.Parent.Controls["mobjToolBarMain"] as ToolBar;
            if (this.Parent.Parent.Controls["mobjToolBarMain"] is ToolBar) return TbarLocal = this.Parent.Controls["mobjToolBarMain"] as ToolBar;

            return null;
        }
        public string GetTitle()
        {
            return _title;
        }
        public string GetLanguage()
        {
            return language;
        }
        protected bool IsPermis(int id)
        {
            return GetMainForm().IsPermis(id);
        }
        protected bool _isCheck = false;
        protected class MyPermisControl
        {
            public int idHandle;
            public object obj;
            public MyPermisControl(int id, object control)
            {
                idHandle = id;
                obj = control;
            }
        };

        public ModuleParent()
        {
            this.warnProvider.Icon = new Gizmox.WebGUI.Common.Resources.IconResourceHandle("warning16x16.png");
            
        }
        protected virtual void AllowEditLanguage() { }
        protected override void OnLoad(EventArgs e)
        {
            FormatDate();
            GetMainForm();
            if (_tvList != null)
            {
                _tvList.AfterSelect += new TreeViewEventHandler(_tvList_AfterSelect);
            }

            if (_dgvFilter != null)
            {
                if (_strTableName != null)
                {
                    if (!_dgvFilter.LoadData(GetMainForm().PODInfo.USER_ID, _strType, _strTableName, GetMainForm().PODInfo.Business_ID))
                        _dgvFilter.LoadData(GetMainForm().PODInfo.USER_ID, _strTableName, GetMainForm().PODInfo.Business_ID);
                }
                else _dgvFilter.LoadData(GetMainForm().PODInfo.USER_ID, _strType, GetMainForm().PODInfo.Business_ID);
                // reloadList();
            }

            if (_dgvList != null)
            {
                FormatDate();
                _layout = new GridLayout(MainForm.ServerPath + "Resources\\Layout\\", MainForm.ServerPath + "Documents\\Layout\\" + GetMainForm().PODInfo.USER_ID + "\\", _strType);
                if (_isCheck) _layout.SetUpDGVWithCheck(_dgvList);
                else _layout.SetUpDGV(_dgvList);
                _dgvList.CellClick += new DataGridViewCellEventHandler(_dgvList_CellClick);
                _dgvList.MenuClick += new MenuEventHandler(_dgvList_MenuClick);
            }
            reloadList();

            base.OnLoad(e);

            LoadLanguage(language);
            SetPermission();
            ThrowMsg("Command: " + _strType);


        }

        void _tvList_AfterSelect(object sender, TreeViewEventArgs e)
        {
            loadRecord(e.Node);
        }


        protected void ThrowMsg(string sErr)
        {
            if (MainForm == null)
            {
                MainForm = this.Parent.Parent as MainForm;
                if (MainForm == null)
                {
                    Forms.frmMain frm = this.Parent.Parent as Forms.frmMain;
                    frm.ThrowMsg(sErr);

                    MainForm = frm.MainForm;
                }
                else MainForm.SetMsg(sErr);

            }
            else MainForm.SetMsg(sErr);
        }
        protected void ShowMsg(string sErr)
        {
            MessageBox.Show(sErr);
        }
        private void SetPermission()
        {
            if (_permisControl == null || _permisControl.Count == 0)
                InitPermisControl();
            foreach (MyPermisControl it in _permisControl)
            {
                if (it.obj is Control)
                {
                    if (IsPermis(it.idHandle))
                    {
                        ((Control)it.obj).Visible = true;
                    }
                    else ((Control)it.obj).Visible = false;
                }


                else if (it.obj is ToolBarButton)
                {
                    if (IsPermis(it.idHandle))
                    {
                        ((ToolBarButton)it.obj).Visible = true;
                    }
                    else ((ToolBarButton)it.obj).Visible = false;
                }
            }
        }

        protected virtual void LoadLanguage(string language) { }
        public virtual void SetTitle(string title)
        {
            _title = title;
            if (this.Parent is Gizmox.WebGUI.Forms.HeaderedPanel)
            {
                if (this.Parent.Text != title)
                    this.Parent.Text = title;
            }
        }
        protected MainForm GetMainForm()
        {
            if (MainForm == null)
            {
                if (this.Parent != null)
                {
                    MainForm = this.Parent.Parent as MainForm;
                    if (MainForm == null)
                    {
                        Forms.frmMain frm = this.Parent.Parent as Forms.frmMain;
                        MainForm = frm.MainForm;

                    }
                }
            }
            return MainForm;
        }
        protected List<string> _btnProcess = new List<string>(new string[] { "K", "S" });
        protected string _strsErrcheckExists = "";
        protected Dictionary<string, ToolBarButton> _arrButton = new Dictionary<string, ToolBarButton>();
        protected virtual void SetupToolBar(string strAction)
        {
            ToolBar tbarLocal = GetTbarLocal();
            bool on = true, off = false;
            if (tbarLocal == null) return;

            switch (strAction)
            {
                case "C":
                case "O":
                case "A":
                    foreach (ToolBarButton button in tbarLocal.Buttons)
                    {
                        if (!_btnProcess.Contains(button.Name)) { if (button.Enabled != off) button.Enabled = off; }
                        else { if (button.Enabled != on) button.Enabled = on; }
                    }
                    break;
                default:
                    foreach (ToolBarButton button in tbarLocal.Buttons)
                    {
                        if (!_btnProcess.Contains(button.Name)) { if (button.Enabled != on) button.Enabled = on; }
                        else { if (button.Enabled != off) button.Enabled = off; }
                    }

                    break;
            }

        }
        /*   protected void UpdateControlLanguage(object obj)
           {
               if (obj is Control)
               {
                   Control control = obj as Control;

                   Ddb.frmInputData frm = new Ddb.frmInputData();
                   frm.Default = control.Text;
                   frm.FormClosed += (form, args) =>
                   {
                       if (((Form)form).DialogResult == DialogResult.OK)
                       {
                           control.Text = frm.valuereturn;
                           clsConfigurarion.SetLabel(this.ToString(), control, language);
                       }
                   };
                   frm.ShowDialog();
               }
               else if (obj is DataGridViewColumn)
               {
                   DataGridViewColumn col = obj as DataGridViewColumn;
                   Ddb.frmInputData frm = new Ddb.frmInputData();
                   frm.Default = col.HeaderText;
                   frm.FormClosed += (form, args) =>
                   {
                       if (((Form)form).DialogResult == DialogResult.OK)
                       {
                           col.HeaderText = frm.valuereturn;
                           clsConfigurarion.SetLabel(this.ToString(), col.Name, col.HeaderText, language);
                       }
                   };
                   frm.ShowDialog();
               }
           }
           protected void UpdateControlLanguage(object obj, string key)
           {
               if (obj is Control)
               {
                   Control control = obj as Control;

                   Ddb.frmInputData frm = new Ddb.frmInputData();
                   frm.Default = control.Text;
                   frm.FormClosed += (form, args) =>
                   {
                       if (((Form)form).DialogResult == DialogResult.OK)
                       {
                           control.Text = frm.valuereturn;
                           clsConfigurarion.SetLabel(this.ToString(), key, control.Text, language);
                       }
                   };
                   frm.ShowDialog();
               }
               else if (obj is DataGridViewColumn)
               {
                   DataGridViewColumn col = obj as DataGridViewColumn;
                   Ddb.frmInputData frm = new Ddb.frmInputData();
                   frm.Default = col.HeaderText;
                   frm.FormClosed += (form, args) =>
                   {
                       if (((Form)form).DialogResult == DialogResult.OK)
                       {
                           col.HeaderText = frm.valuereturn;
                           clsConfigurarion.SetLabel(this.ToString(), key, col.HeaderText, language);
                       }
                   };
                   frm.ShowDialog();
               }
           }*/
        protected void dgvList_MenuClick(object objSource, MenuItemEventArgs objArgs)
        {
            //DataGridView dgvList = objSource as DataGridView;
            //GetMainForm().UpdateControlLanguage(this.ToString(), dgvList.Columns[((DataGridViewTextBoxCell)objArgs.Member).ColumnIndex]);
        }
        protected void Control_DoubleClick(object sender, EventArgs e)
        {
            //GetMainForm().UpdateControlLanguage(this.ToString(), sender as Control);

        }
        protected void Control_MenuClick(object objSource, MenuItemEventArgs objArgs)
        {
            //GetMainForm().UpdateControlLanguage(this.ToString(), objArgs.Source as Control);
        }
        protected void tabMain_MenuClick(object objSource, MenuItemEventArgs objArgs)
        {
            //TabControl tab = objArgs.Source as TabControl;
            //if (tab != null)
            //    GetMainForm().UpdateControlLanguage(this.ToString(), tab.SelectedTab as Control);
        }

        protected void tabMain_DoubleClick(object sender, EventArgs e)
        {
            //TabControl tab = sender as TabControl;
            //GetMainForm().UpdateControlLanguage(this.ToString(), tab.SelectedTab as Control);
        }
        protected void tool_MenuClick(object objSource, MenuItemEventArgs objArgs)
        {
            //ToolBarButton btn = ((ToolBarButton)objArgs.Source);
            //if (btn != null)
            //    GetMainForm().UpdateControlLanguage(this.ToString(), btn);

        }

    }
}